﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms.VisualStyles;
using OpenSoftStore.BusinessLogic.Money;
using OpenSoftStore.Orm;
using OpenSoftStore.Orm.Logic;
using OpenSoftStore.Orm.Model;
using OpenSoftStore.Orm.View;

namespace OpenSoftStore.BusinessLogic.Provider
{
    public class ProviderLogic : ABusinessLogic
    {

        private static SpaEntities spa;

        public MoneyLogic MoneyBll;

        public ProviderLogic()
        {
            spa = new SpaEntities();
            MoneyBll = new MoneyLogic();
        }

        public DataTable GetProviderPayInfo(string strWhere = "", string condition = "")
        {
            var provider = new List<T_Provider>();//所有供应商
            var listPayInfo = new List<V_ProviderPayInfo>();

            string sql = "Select * from (Select Id,Name,YuFu,  iif(isnull([_In_AllNeed]),0,[_In_AllNeed]) as In_AllNeed,";
            sql += " iif(isnull([_In_AllReal]),0,[_In_AllReal]) as In_AllReal, iif(isnull([_In_AllFavor]),0,[_In_AllFavor]) as In_AllFavor, ";
            sql += " iif(isnull([_In_AllOwed]),0,[_In_AllOwed]) as In_AllOwed, YuShou,";
            sql += " iif(isnull([_Out_AllNeed]),0,[_Out_AllNeed]) as Out_AllNeed, iif(isnull([_Out_AllReal]),0,[_Out_AllReal]) as Out_AllReal,";
            sql += " iif(isnull([_Out_AllFavor]),0,[_Out_AllFavor]) as Out_AllFavor, iif(isnull([_Out_AllOwed]),0,[_Out_AllOwed]) as Out_AllOwed, Tel,Address,TreeId";
            sql += " from (Select * from [T_Provider] as t1 left join (Select Sum(NeedPay) as _In_AllNeed,Sum(RealPay) as _In_AllReal, Sum(FavorMoney) as _In_AllFavor, ";
            sql += " Sum(NeedPay) - Sum(RealPay) - Sum(FavorMoney) as _In_AllOwed, BuzUserId  from [T_StoreIO] " + strWhere + "  And ( buzType = '进货' Or BuzType = '调拨调入' ) ";
            sql += " Group BY BuzUserId) as t2 on t1.Id = t2.BuzUserId) as t1 left join (Select Sum(NeedPay) as _Out_AllNeed, Sum(RealPay) as _Out_AllReal,";
            sql += " Sum(FavorMoney) as _Out_AllFavor, Sum(NeedPay) - Sum(RealPay) - Sum(FavorMoney) as _Out_AllOwed, BuzUserId  ";
            sql += " from [T_StoreIO] " + strWhere + "  And ( buzType = '向供应商退货' Or BuzType = '调拨调出' )  Group BY BuzUserId ) as t2 on t1.Id = t2.BuzUserId ) as t1";
            sql += condition;
            var data = Spa.RunSqLcmdDataSet(sql);

            if (data.Tables == null || data.Tables.Count == 0)
            {
                return new DataTable();
            }
            return data.Tables[0];
        }

        public DataTable GetProviderList(string strWhere = "", string strOrderBy = "")
        {
            string sql = " select P.*,T.Name as TreeName from T_Provider as P inner join T_Tree as T on P.TreeId=T.Id ";
            if (!string.IsNullOrEmpty(strWhere)) sql += strWhere;
            if (!string.IsNullOrEmpty(strOrderBy)) sql += strOrderBy;
            var data = spa.RunSqLcmdDataSet(sql);
            if (data.Tables == null || data.Tables.Count == 0) return new DataTable();
            return data.Tables[0];
        }

        public IEnumerable<V_Provider> GetProviderView(string strWhere = "", string strOrderBy = "")
        {
            string sql = " select P.*,T.Name as TreeName from T_Provider as P inner join T_Tree as T on P.TreeId=T.Id ";
            if (!string.IsNullOrEmpty(strWhere)) sql += strWhere;
            if (!string.IsNullOrEmpty(strOrderBy)) sql += strOrderBy;
            return Spa.SelectWhere<V_Provider>(sql);
        }

        public List<V_PayIn> GetProviderPayIn(string id, string strWhere)
        {
            if (string.IsNullOrEmpty(id)) return null;
            var panIns = new List<V_PayIn>();

            string sql = " select *,NeedPay-RealPay as WfPay from T_StoreIO where BuzUserId ='" + id + "' and RealPay < NeedPay" + strWhere;
            var data = Spa.SelectWhere<V_PayIn>(sql).ToList();
            return data;

        }


        public bool Save(IEnumerable<V_PayIn> payIns, T_ProviderPay providerPay, T_Provider provider)
        {
            bool b = true;
            var lis = new List<T_ProviderPayItem>();
            var storeIos = new List<T_StoreIO>();
            foreach (var payIn in payIns)
            {
                var itemModel = new T_ProviderPayItem();
                var storeIo = (T_StoreIO)payIn;
                storeIo.RealPay = payIn.WfPay;
                storeIos.Add(storeIo);

                itemModel.PayId = providerPay.Id;
                itemModel.StoreIOId = payIn.Id;
                itemModel.Pay = payIn.NeedPay;
                lis.Add(itemModel);
            }
            if (provider != null)
                Spa.Update(provider);

            if (Spa.Add(providerPay) == 0) b = false; //保存支付
            Spa.AddObjects(lis);//保存子项
            Spa.SaveChanges();

            foreach (var v in storeIos)
            {
                string whereStr = string.Format("update T_StoreIO set RealPay= RealPay +{0} where Id='{1}' ", v.RealPay, v.Id);
                if (!Spa.RunSqLcmd(whereStr))
                    b = false;
            }

            var lMoney = new L_Money
            {
                TreeId = "e04e9fb6-0ce8-4a8a-a9a6-67db293fda2f",
                TreeName = "付款给供应商",
                Type = providerPay.Type,
                ObjectId = providerPay.Id,
                BankPayMoney = providerPay.BankPay,
                CashPayMoney = providerPay.CashPay,
                BankAccountId = providerPay.BankAccountId,
                AdminId = providerPay.AdminId,
                ShopId = providerPay.ShopId
            };
            MoneyBll.AddMoeny(lMoney);

            return b;
        }

        public DataTable GetPayInItem(string whereStr = "", string orderStr = "")
        {
            string sql = " select T_ProviderPayItem.Pay,T_StoreIO.BuzType,T_StoreIO.AddTime,T_StoreIO.StroeIONo ";
            sql += " from T_ProviderPayItem inner join T_StoreIO on T_StoreIO.Id=T_ProviderPayItem.StoreIOId ";
            sql += whereStr;
            sql += orderStr;
            var data = Spa.RunSqLcmdDataSet(sql);
            if (data.Tables == null || data.Tables.Count == 0)
                return new DataTable();
            else
                return data.Tables[0];

        }

        public DataTable GetProviderPay(string strWhere = "", string strOrderBy = "")
        {
            string sql = " select PP.*,P.Name as ProviderName from T_ProviderPay as PP inner join T_Provider as P on P.Id=PP.ProviderId ";
            if (!string.IsNullOrEmpty(strWhere)) sql += strWhere;
            if (!string.IsNullOrEmpty(strOrderBy)) sql += strOrderBy;
            var data = spa.RunSqLcmdDataSet(sql);
            if (data.Tables == null || data.Tables.Count == 0) return new DataTable();
            return data.Tables[0];
        }

        public bool DeletePay(string PayId)
        {
            var data = Spa.Where<T_ProviderPay>(p => p.Id == PayId).FirstOrDefault();
            string updateProSql = " Update T_Provider set YuFu=" + data.BeforLastValue + "where Id='" + data.ProviderId + "'";
            Spa.RunSqLcmd(updateProSql);
            string deletePropay = "delete from T_ProviderPay where Id='" + PayId + "'";
            Spa.RunSqLcmd(deletePropay);
            string deletePayItem = "delete from T_ProviderPayItem where PayId='" + PayId + "'";
            Spa.RunSqLcmd(deletePayItem);
            string deleteMoney = @"delete  from T_Money where ObjectId='" + PayId + "'";
            Spa.RunSqLcmd(deleteMoney);
            return true;
        }
    }
}
